package cn.xfdzx.android.apps.shop.activity.ruzhu;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import java.io.File;
import java.io.IOException;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.activity.MoreAddressMapActivity;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.IdCardBeen;
import cn.xfdzx.android.apps.shop.bean.LicenseImgBeen;
import cn.xfdzx.android.apps.shop.bean.Ruzhu_StepBean;
import cn.xfdzx.android.apps.shop.bean.ShopIn1Been;
import cn.xfdzx.android.apps.shop.bean.Store_ruzhuBean;
import cn.xfdzx.android.apps.shop.bean.UploadImgBeen;
import cn.xfdzx.android.apps.shop.contract.Store_InfoContract;
import cn.xfdzx.android.apps.shop.presenter.Store_InfoPresenter;
import cn.xfdzx.android.apps.shop.util.GlideEngine;
import cn.xfdzx.android.apps.shop.util.ShopCarPopupWindow;
import cn.xfdzx.android.apps.shop.util.UtilsLog;
import cn.xfdzx.android.apps.shop.widget.WheelPicker;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static cn.xfdzx.android.apps.shop.apps.Constants.APP_TOKEN;
import static cn.xfdzx.android.apps.shop.apps.Constants.START_CODE;

public class Store_informationActivity extends BaseMvpActivity<Store_InfoPresenter> implements Store_InfoContract.View {
    public Context mContext;

    @BindView(R.id.ll_state)
    LinearLayout llState;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.tv_title_name)
    TextView tvTitleName;
    @BindView(R.id.ett_retail_shop_name)
    EditText ettRetailShopName;
    @BindView(R.id.ll_retail_shop_name)
    LinearLayout llRetailShopName;
    @BindView(R.id.hint_retail_shop_name)
    TextView hintRetailShopName;
    @BindView(R.id.tv_retail_qualifications_name)
    TextView tvRetailQualificationsName;
    @BindView(R.id.tv_found_address)
    TextView tvFoundAddress;
    @BindView(R.id.ll_address_shop_name)
    LinearLayout llAddressShopName;
    @BindView(R.id.ett_xiangxi_address)
    EditText ettXiangxiAddress;
    @BindView(R.id.tv_retail_shop_name)
    TextView tvRetailShopName;
    @BindView(R.id.ll_shop_photo)
    LinearLayout llShopPhoto;
    @BindView(R.id.im_mentouzhao)
    ImageView imMentouzhao;
    @BindView(R.id.rl_shop_photo)
    RelativeLayout rlShopPhoto;
    @BindView(R.id.ll_shop_photo_inside)
    LinearLayout llShopPhotoInside;
    @BindView(R.id.im_diannenzhao)
    ImageView imDiannenzhao;
    @BindView(R.id.rl_shop_photo_inside)
    RelativeLayout rlShopPhotoInside;
    @BindView(R.id.ett_contacts_name)
    EditText ettContactsName;
    @BindView(R.id.ll_contacts_name)
    LinearLayout llContactsName;
    @BindView(R.id.hint_contacts_name)
    TextView hintContactsName;
    @BindView(R.id.ett_contacts_phone)
    EditText ettContactsPhone;
    @BindView(R.id.ll_contacts_phone)
    LinearLayout llContactsPhone;
    @BindView(R.id.hint_contacts_phone)
    TextView hintContactsPhone;
    @BindView(R.id.ett_peroid_count)
    EditText ettPeroidCount;
    @BindView(R.id.ll_peroid_count)
    LinearLayout llPeroidCount;
    @BindView(R.id.tv_select_cooperation_term)
    TextView tvSelectCooperationTerm;
    @BindView(R.id.ll_branch_count)
    LinearLayout llBranchCount;
    @BindView(R.id.ett_invite_number)
    EditText ettInviteNumber;
    @BindView(R.id.ll_invite_number)
    LinearLayout llInviteNumber;
    @BindView(R.id.tv_yi_du)
    TextView tvYiDu;
    @BindView(R.id.hint_shop_count)
    TextView hintShopCount;
    private ShopCarPopupWindow yearPopupWindow;
    private WheelPicker wheelPicker;
    private List<String> yearList = new ArrayList<>();
    private int contract_year = 0;//合作期限
    private String lng, lat;//
    protected Handler handler = new Handler();
    private String store_mentouzhao = "", store_dianneizhao = "";
    private ShopIn1Been shopIn1Been;
    private Gson gson = new Gson();
    private int years;
    private String storeid;
    private String step = "one";
    private Ruzhu_StepBean ruzhu_stepBean;
    private String num;
    private int t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0;
    String telRegex = "^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\\d{8}$";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。

    @Override
    public int getLayoutId() {
        return R.layout.activity_store_information;
    }

    @Override
    public void initView() {
        mPresenter = new Store_InfoPresenter();
        mPresenter.attachView(this);

        mPresenter.getStep_Ruzhu(step);
        popupWindow();
        //     editListen();
        ChangeYears();
        mContext = this;
    }

    private void ChangeYears() {
        if (tvSelectCooperationTerm.getText().equals("一年")) {
            years = 1;
        } else if (tvSelectCooperationTerm.getText().equals("两年")) {
            years = 2;
        } else if (tvSelectCooperationTerm.getText().equals("三年")) {
            years = 3;
        }
    }

    @Override
    public void getStateType(Store_ruzhuBean bean) {

    }

    @Override
    public void getRuzhuStep(Ruzhu_StepBean bean) {
        Intent intent = getIntent();
        storeid = intent.getStringExtra("stoid");
        Log.e("zhuangtai", storeid + "");

        ruzhu_stepBean = new Ruzhu_StepBean();
        setText(bean);//回显


    }

    @Override
    public void oneLicenseImgSuccess(LicenseImgBeen bean) {

    }

    @Override
    public void onIdCardSuccess(IdCardBeen bean) {

    }

    @Override
    public void onIdCardSuccessguanli(IdCardBeen bean) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void onError(Throwable throwable) {

    }


    @OnClick({R.id.iv_back, R.id.tv_found_address, R.id.im_mentouzhao, R.id.im_diannenzhao, R.id.tv_select_cooperation_term, R.id.tv_yi_du})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_found_address:
                //跳转到更多地址页面
                //跳转到选择收货地址
                Intent intent_moer_address = new Intent(this, MoreAddressMapActivity.class);
                startActivityForResult(intent_moer_address, START_CODE);
                break;
            case R.id.im_mentouzhao:
                selectImage(imMentouzhao);
                break;
            case R.id.im_diannenzhao:
                selectImage(imDiannenzhao);
                break;
            case R.id.tv_select_cooperation_term:
                yearPopupWindow.showPopupWindow();
                break;
            case R.id.tv_yi_du:

                if (ettRetailShopName.getText().toString() == null || ettRetailShopName.getText().toString().equals("")) {
                    hintRetailShopName.setVisibility(View.VISIBLE);
                } else {
                    hintRetailShopName.setVisibility(View.GONE);
                    t1 = 1;
                }
                if (ettXiangxiAddress.getText().toString() == null || ettXiangxiAddress.getText().toString().equals("")) {
                } else {
                    t2 = 1;
                }
                if (tvFoundAddress.getText().toString() == null || tvFoundAddress.getText().toString().equals("")) {
                } else {
                    t3 = 1;
                }
                if (store_mentouzhao.equals("")) {
                } else {
                    t4 = 1;
                }
                if (store_dianneizhao.equals("")) {
                } else {
                    t5 = 1;
                }
                if (ettContactsName.getText().toString() == null || ettContactsName.getText().toString().equals("")) {
                    hintContactsName.setVisibility(View.VISIBLE);
                } else {
                    hintContactsName.setVisibility(View.GONE);
                    t6 = 1;
                }
                if (ettContactsPhone.getText().toString() == null || ettContactsPhone.getText().toString().equals("")) {
                    hintContactsPhone.setVisibility(View.VISIBLE);
                } else {
                    hintContactsPhone.setVisibility(View.GONE);
                    t7 = 1;
                }
                if (ettPeroidCount.getText().toString() == null || ettPeroidCount.getText().toString().equals("")) {
                    hintShopCount.setVisibility(View.VISIBLE);
                } else {
                    hintShopCount.setVisibility(View.GONE);
                    t8 = 1;
                }
                if (years == 0) {
                } else {
                    t9 = 1;
                }
                if (ettContactsPhone.getText().toString().matches(telRegex) == true) {
                    t10 = 1;
                }
                if (t1 == 1 && t2 == 1 && t3 == 1 && t4 == 1 && t5 == 1 && t6 == 1 && t7 == 1 && t8 == 1 && t9 == 1 && t10 == 1) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("step", step);
                    map.put("store_id", storeid);
                    map.put("name", ettRetailShopName.getText() + "");
                    map.put("address", ettXiangxiAddress.getText());
                    map.put("store_category", 1);
                    map.put("lng", lng);
                    map.put("lat", lat);
                    map.put("location_address", tvFoundAddress.getText() + "");
                    map.put("front_door_photo", store_mentouzhao);
                    map.put("in_store_photo", store_dianneizhao);
                    map.put("realname", ettContactsName.getText());
                    map.put("mobile", ettContactsPhone.getText());
                    map.put("store_num", ettPeroidCount.getText());
                    map.put("years_of_cooperation", years);
                    map.put("inv_code", ettInviteNumber.getText());
                    Log.e("ceasd", map.toString());
                    mPresenter.getState_Ruzhu(map);
                    Intent intent = new Intent(this, InformationActivity.class);
                    startActivity(intent);
                } else if (t10 != 1) {
                    if (ettContactsPhone.getText().toString().equals("") == false && ettContactsPhone.getText().toString() != null) {
                        Toast.makeText(mContext, "手机号输入错误！", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(mContext, "请确认信息输入完整后提交！", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    private void popupWindow() {
        yearPopupWindow = new ShopCarPopupWindow(this, R.layout.pw_unit);
        wheelPicker = yearPopupWindow.getRootView().findViewById(R.id.up_unit);
        yearList.add("一年");
        yearList.add("两年");
        yearList.add("三年");
        wheelPicker.setDataList(yearList);

        yearPopupWindow.getRootView().findViewById(R.id.tv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                yearPopupWindow.shareClose();
            }
        });

        yearPopupWindow.getRootView().findViewById(R.id.tv_queren).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                contract_year = wheelPicker.getCurrentPosition() + 1;
                tvSelectCooperationTerm.setText(yearList.get(wheelPicker.getCurrentPosition()));
                yearPopupWindow.shareClose();
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == START_CODE) {
                String addressName = data.getStringExtra("address_name");
                String district = data.getStringExtra("district");
                String city = data.getStringExtra("city");
                lng = data.getStringExtra("lontitude");
                lat = data.getStringExtra("latitude");

                if (null != addressName) {
                    tvFoundAddress.setText(city + district + addressName);
                    tvFoundAddress.setTextColor(getResources().getColor(R.color.color_333333));
                }
            }
        }
    }

    private void editListen() {

        ettRetailShopName.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {

                if (s.length() >= 1) {
                    hintRetailShopName.setVisibility(View.GONE);
                } else {
                    hintRetailShopName.setVisibility(View.VISIBLE);
                }


            }

        });
        ettContactsName.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {

                if (s.length() >= 1) {
                    hintContactsName.setVisibility(View.GONE);
                } else {
                    hintContactsName.setVisibility(View.VISIBLE);
                }


            }

        });
        ettContactsPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {

                if (s.length() >= 1) {
                    hintContactsPhone.setVisibility(View.GONE);
                } else {
                    hintContactsPhone.setVisibility(View.VISIBLE);
                }


            }

        });
        ettPeroidCount.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {

                if (s.length() >= 1) {
                    hintShopCount.setVisibility(View.GONE);
                } else {
                    hintShopCount.setVisibility(View.VISIBLE);
                }


            }

        });
    }

    public void selectImage(ImageView imageView) {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage()).maxSelectNum(1)
                .loadImageEngine(GlideEngine.createGlideEngine())
                .minSelectNum(1).imageSpanCount(4)
                .selectionMode(PictureConfig.SINGLE)
                .compress(true)
                .minimumCompressSize(1000)
                .compressQuality(60)
                .isCamera(true)
                .previewImage(true)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        // onResult Callback
                        if (result.size() != 0) {
                            UtilsLog.error("dizhi", result.get(0).getCompressPath());
//                                    new File(result.get(0).getPath())
//                                    mPresenter.upload(new File(result.get(0).getPath()));
                            showLoading();
                            upLoadFiles(Constants.BASE_URL + "/addons/shimmer_liveshop/index.php/api/6/3/plugin/merch/common/apply/uploadImg", new File(result.get(0).getCompressPath()), new XFDShopInActivity.ConnectListener() {
                                @Override
                                public void connectSuccess(String result) {
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            hideLoading();
                                            try {
                                                Gson gson = new Gson();
                                                UploadImgBeen uploadImgBeen = gson.fromJson(result, UploadImgBeen.class);
                                                if (uploadImgBeen.getErrno().equals("200")) {

                                                    RoundedCorners roundedCorners = new RoundedCorners(10);
                                                    //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
                                                    RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);
                                                    Glide.with(mContext).load(uploadImgBeen.getData().getSrc()).apply(options.transform(new CenterCrop(), roundedCorners)).into(imageView);
                                                    if (imageView == imMentouzhao) {

                                                        store_mentouzhao = uploadImgBeen.getData().getSrc();
                                                        Log.e("ceasd", store_mentouzhao + "++");
                                                    } else if (imageView == imDiannenzhao) {
                                                        store_dianneizhao = uploadImgBeen.getData().getSrc();
                                                        Log.e("diannenzhao", store_dianneizhao);
                                                    }

                                                } else {
                                                    Toast.makeText(mContext, uploadImgBeen.getMessage(), Toast.LENGTH_SHORT).show();
                                                }
                                            } catch (Exception e) {
                                                Toast.makeText(mContext, "上传失败", Toast.LENGTH_SHORT).show();

                                            }
                                        }
                                    });

                                }

                                @Override
                                public void connectFailed(String error) {
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            hideLoading();

                                        }
                                    });
                                }
                            });
                        }
                    }

                    @Override
                    public void onCancel() {
                        // onCancel Callback
                    }
                });
    }

    public void upLoadFiles(final String url, File file, final XFDShopInActivity.ConnectListener connectListener) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().proxy(Proxy.NO_PROXY).connectTimeout(60 * 1000, TimeUnit.MILLISECONDS)
                .readTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
                .writeTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
                .build();
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
        multipartBodyBuilder.setType(MultipartBody.FORM);
        //遍历map中所有参数到builder
        multipartBodyBuilder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file));
        //构建请求体
        RequestBody requestBody = multipartBodyBuilder.build();
        Request.Builder RequestBuilder = new Request.Builder();
        RequestBuilder.url(url);// 添加URL地址
        RequestBuilder.post(requestBody);
        RequestBuilder.addHeader("Authori-zation", "Bearer " + APP_TOKEN);
        Request request = RequestBuilder.build();

        final Call call = okHttpClient.newCall(request);
        //异步get请求
        call.enqueue(new Callback() {
                         @Override
                         public void onFailure(Call call, IOException e) {
                             connectListener.connectFailed(e.toString());
                             UtilsLog.error("错误", e.toString());
                         }

                         @Override
                         public void onResponse(Call call, Response response) throws IOException {
                             String result = response.body().string();
                             connectListener.connectSuccess(result);
                             UtilsLog.error("成功", result);
                         }
                     }
        );
    }

    private void setText(Ruzhu_StepBean bean) {
        ChangeData(bean);

        ettRetailShopName.setText(bean.getData().getName());
        tvFoundAddress.setText(bean.getData().getLocation_address());
        ettXiangxiAddress.setText(bean.getData().getAddress());

        RoundedCorners roundedCorners = new RoundedCorners(10);
        //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
        RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);
        Glide.with(mContext).load(bean.getData().getFront_door_photo()).apply(options.transform(new CenterCrop(), roundedCorners)).into(imMentouzhao);
        Glide.with(mContext).load(bean.getData().getIn_store_photo()).apply(options.transform(new CenterCrop(), roundedCorners)).into(imDiannenzhao);
        store_mentouzhao = bean.getData().getFront_door_photo();
        store_dianneizhao = bean.getData().getIn_store_photo();
        lat = bean.getData().getLat();
        lng = bean.getData().getLng();
        ettContactsName.setText(bean.getData().getRealname());
        ettContactsPhone.setText(bean.getData().getMobile());
        ettPeroidCount.setText(bean.getData().getStore_num());

        tvSelectCooperationTerm.setText(num);
    }

    private void ChangeData(Ruzhu_StepBean bean) {
        if (bean.getData().getYears_of_cooperation().equals(1)) {
            num = "一年";
        } else if (bean.getData().getYears_of_cooperation().equals(2)) {
            num = "两年";
        } else {
            num = "三年";
        }
    }
}